<template>
  <div class="my">
    <h1>滚动加载</h1>
    <div style="display: flex">
      <div
        style="
          height: 400px;
          width: 400px;
          overflow-y: scroll;
          padding: 10px;
          box-sizing: border-box;
          border: 1px solid #ddd;
          margin-right: 20px;
        "
        id="one"
      >
        <div class="result" v-for="comment in comments" :key="comment.id">
          <div>{{ comment.email }}</div>
          <div>{{ comment.id }}</div>
        </div>
        <infinite-loading @infinite="load" target="#one" />
      </div>
      <div
        style="
          height: 400px;
          width: 350px;
          overflow-y: scroll;
          padding: 10px;
          box-sizing: border-box;
          border: 1px solid #ddd;
        "
        class="one"
      >
        <div class="result" v-for="comment in comments" :key="comment.id">
          <div>{{ comment.email }}</div>
          <div>{{ comment.id }}</div>
        </div>
        <infinite-loading @infinite="load" target=".one" />
      </div>
      <div
        style="
          height: 400px;
          width: 350px;
          overflow-y: scroll;
          padding: 10px;
          box-sizing: border-box;
          border: 1px solid #ddd;
        "
        class="pinia"
      >
        <div class="result" v-for="item in newList" :key="item.id">
          <div>{{ item.email }}</div>
          <div>{{ item.id }}</div>
        </div>
        <infinite-loading @infinite="loadList" target=".pinia" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { useList } from '@/store/list'
  import request from '@/utils/request'
  interface CommentType {
    email?: string
    id?: string
  }

  // 实例化
  const { newList, getListRequest }: any = useList()

  // 请求 pinia
  const loadList = ($state: any) => getListRequest($state)

  // 模拟个滚动加载
  let comments = ref<Array<CommentType>>([])
  let page = 1

  const load = async ($state: { complete: () => void; loaded: () => void; error: () => void }) => {
    request({
      url: '/comments?_limit=20&_page=' + page,
    })
      .then((res: any) => {
        if (res.length < 20) {
          $state.complete()
        } else {
          comments.value.push(...(res as []))
          $state.loaded()
        }
        page++
      })
      .catch(() => {
        $state.error()
      })
  }
</script>
<style lang="scss" scoped>
  .my {
    background-color: cadetblue;
    width: 100%;
    height: 100%;
  }
  .result {
    display: flex;
    flex-direction: column;
    gap: 5px;
    font-weight: 300;
    padding: 10px;
    text-align: center;
    margin: 0 auto 10px auto;
    background: #eceef0;
    border-radius: 10px;
  }
</style>
